package com.example.data.factory.common.util;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.data.factory.common.common.StringConstant;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Component
public class CommonUtil {
    //获取当前登录用户的基本信息工具类(前提是在登录的时候需要将登录的用户信息存入到token中，这样发送请求的时候用户信息就被携带在请求体中了)
    @Resource
    private JwtUtil jwtUtil;

    /**
     * 从当前请求中提取用户名
     */
    public String extractUsernameFromRequest(HttpServletRequest request) {
        // 从请求头中获取 Token
        String token = request.getHeader ( StringConstant.AUTHORIZATION );
        //判断token是否存在
        if (token == null || token.isEmpty ()) {
            throw new RuntimeException ( "Token 为空" );
        }

        // 去掉 Bearer 前缀
        if (token.startsWith ( "Bearer " )) {
            token = token.substring ( 7 );
        }

        try {
            // 验证 Token 并获取用户名
            DecodedJWT tokenInfo = jwtUtil.verifyToken ( token );
            return tokenInfo.getClaim ( "username" ).asString ();
        } catch (Exception e) {
            throw new RuntimeException ( "Token 验证失败: " + e.getMessage () );
        }
    }
}
